package com.xinfu.newproject.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.alley.van.VanGogh;
import com.alley.van.helper.VanCropType;
import com.alley.van.helper.VanMediaFilter;
import com.alley.van.helper.VanMediaType;
import com.alley.van.model.VanConfig;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.xinfu.newproject.R;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.bean.person.bean.PersonBean;
import com.xinfu.newproject.bean.up_image.UpImageBean;
import com.xinfu.newproject.contants.Contants;
import com.xinfu.newproject.presenter.PersonPresenter;
import com.xinfu.newproject.presenter.UpImagePresenter;
import com.xinfu.newproject.test.GifSizeFilter;
import com.xinfu.newproject.test.GlideImageLoader;
import com.xinfu.newproject.test.VanToast;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.GetImagePathUtil;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.view.IView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.xinfu.newproject.contants.Constant.COMMUNITY;
import static com.xinfu.newproject.contants.Constant.COMMUNITYID;
import static com.xinfu.newproject.contants.Constant.LOGIN;
import static com.xinfu.newproject.contants.Constant.TENANTID;
import static com.xinfu.newproject.contants.Constant.USERIMAGE;
import static com.xinfu.newproject.contants.Constant.USERNAME;
import static com.xinfu.newproject.contants.Constant.USERSEX;

public class PersonActivity extends BaseActivity implements IView.IUpPersonView, IView.IUpImageView {

    @BindView(R.id.head_right_text)
    TextView rightTv;

    @BindView(R.id.activity_person_iv)
    ImageView personIv;

    @BindView(R.id.recycler_person_sex)
    TextView sexTv;

    @BindView(R.id.recycler_person_user_name_et)
    EditText realNameTv;

    @BindView(R.id.recycler_person_phone_et)
    TextView phoneTt;

    @BindView(R.id.activity_person_community_tv)
    TextView communityTv;

    private int isImage = 0;
    private ArrayList<String> imageList = new ArrayList<>();
    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_CODE_CAMERA = 32;

    private UpImagePresenter upImagePresenter = new UpImagePresenter(this);
    private PersonPresenter personPresenter = new PersonPresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person);
        ButterKnife.bind(this);
        registerBack();
        initViewBind();
        initLisener();
    }

    private void initLisener() {

    }

    private void initViewBind() {
        setActivityTitle("个人信息");
        rightTv.setText("保存");
        rightTv.setVisibility(View.VISIBLE);
        if (isLogin()) {
            phoneTt.setText(phone);
            if (userImageUrl != null) {
                Glide.with(this).load(userImageUrl).asBitmap().error(R.mipmap.user_normal_icon).into(personIv);
            } else {
                Glide.with(this).load(R.mipmap.user_normal_icon).asBitmap().into(personIv);
            }
            realNameTv.setText(userName);
            if (sex != null) {
                if (sex == 1) {
                    sexTv.setText("男");
                } else if (sex == 2) {
                    sexTv.setText("女");
                } else {
                    sexTv.setText("男");
                }
            } else {
                sexTv.setText("男");
            }
            if (community != null) {
                communityTv.setText(community);
            }

        }

    }


    @OnClick({R.id.head_back, R.id.activity_person_user_img_rl, R.id.activity_person_rl, R.id.activity_person_community_rl, R.id.head_right_text})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_back:
                finish();
                break;
            case R.id.activity_person_user_img_rl:
                onClickCamera();
                break;
            case R.id.activity_person_rl:
                select_sex();
                break;
            case R.id.activity_person_community_rl:
                startActivityForResult(new Intent(this, ChooseCommunityActivity.class), Contants.CHOOSECOMMUNITYDATA);
                break;
            case R.id.head_right_text:
                if (isLogin()) {
                    if (isImage == 1) {
                        upImagePresenter.upImage();
                    } else {
                        personPresenter.upDatePerson();
                    }
                }
                break;
        }
    }

    @Override
    public void permissionGrant(boolean isGranted, int requestCode) {
        super.permissionGrant(isGranted, requestCode);
        if (!isGranted) {
            return;
        }
        switch (requestCode) {
            case 0x0001://拍照
                VanGogh.from(PersonActivity.this)
                        .choose(VanMediaType.ofAll())//拍照时，无效
                        .cameraVisible(true, getPackageName())//拍照时，第一个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_ActivityAnimation)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forCamera(REQUEST_CODE_CAMERA);
                break;

            case 0x0002://从相册选择
                VanGogh.from(PersonActivity.this)
                        .choose(VanMediaType.ofAll())
                        .countable(true)//若开启裁剪，则无效
                        .maxCount(1)
                        .rowCount(3)
                        .cameraVisible(true, getPackageName())//设置在第一个参数为FALSE时，第二个参数无效
                        .withResultSize(1024, 1024)
                        .cropEnable(false, VanCropType.CROP_TYPE_RECTANGLE)//第一个参数为TRUE时，则可选中数量被设为1，此时maxSelectable(9)无效；第一个参数为FALSE时，第二个参数无效
                        .theme(R.style.VanTheme_Dracula)
                        .addFilter(new GifSizeFilter(320, 320, 5 * VanMediaFilter.K * VanMediaFilter.K))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .toast(new VanToast())
                        .imageLoader(new GlideImageLoader())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;

            default:
                break;
        }
    }
    private void select_sex() {
        final CharSequence[] items = new CharSequence[]{"男", "女"};
        String sex = sexTv.getText().toString();
        int poi = 0;
        if (sex.equals("男")) {
            poi = 0;
        } else {
            poi = 1;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择性别：");
        builder.setSingleChoiceItems(items, poi, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                sexTv.setText(items[i]);
                if (sexTv.getText().toString().equals("男")) {
                    sexType = 1;
                } else if (sexTv.getText().toString().equals("女")) {
                    sexType = 2;
                }
                dialogInterface.dismiss();
            }
        }).show();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList = new ArrayList<>();
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:
                    if (VanGogh.obtainResult(data) != null) {
                        if (VanGogh.obtainResult(data).size() > 0) {
                            for (int i = 0; i < VanGogh.obtainResult(data).size(); i++) {
                                pathList.add(GetImagePathUtil.getRealFilePath(this, VanGogh.obtainResult(data).get(i)));
                            }
                        }
                    }
                    if (pathList != null) {
                        if (pathList.size() > 0) {
                            imageList.add(0, pathList.get(0));
                            Glide.with(this).load(pathList.get(0)).asBitmap().error(R.mipmap.user_normal_icon).placeholder(R.mipmap.user_normal_icon).into(personIv);
                        }
                    }
                    isImage = 1;
                    break;
                case REQUEST_CODE_CAMERA:
                    Uri contentUri = VanGogh.obtainCamera();
                    if (contentUri == null) {
                        return;
                    }

                    if (!VanConfig.getInstance().cropEnable) {

                        pathList.add(GetImagePathUtil.getRealFilePath(this, contentUri));
                    }
                    if (pathList != null) {
                        if (pathList.size() > 0) {
                            imageList.add(0, pathList.get(0));
                            Glide.with(this).load(pathList.get(0)).asBitmap().error(R.mipmap.user_normal_icon).placeholder(R.mipmap.user_normal_icon).into(personIv);
                        }
                    }
                    isImage = 1;
                    break;
                case Contants.CHOOSECOMMUNITYDATA:
                    if (data.getStringExtra("name") != null) {
                        communityTv.setText(data.getStringExtra("name"));
                    }
                    break;
            }

        }
    }

    /**
     * 判断是否可以请求数据
     */
    String token, userId, userName, phone, userImageUrl, community, normalProjectId;
    Integer sex;

    private boolean isLogin() {
        LoginBean.ResultBean resultBean;
        String responseIntent = (String) SPUtils.get(this, LOGIN, "0");
        if (!responseIntent.equals("0")) {
            resultBean = new Gson().fromJson(responseIntent, LoginBean.ResultBean.class);
            token = resultBean.getToken();
            userId = resultBean.getUserInfo().getId();
            userName = resultBean.getUserInfo().getUsername();
            phone = resultBean.getUserInfo().getPhone();
            sex = resultBean.getUserInfo().getSex();
            if (resultBean.getUserInfo().getProjectName() != null) {
                community = resultBean.getUserInfo().getProjectName();
                normalProjectId = resultBean.getUserInfo().getProjectId();
            }
            if (!SPUtils.get(this, USERNAME, "0").equals("0")) {
                userName = (String) SPUtils.get(this, USERNAME, "0");
            }
            if (!SPUtils.get(this, USERIMAGE, "0").equals("0")) {
                userImageUrl = (String) SPUtils.get(this, USERIMAGE, "0");
            }
            if ((Integer) SPUtils.get(this, USERSEX, 0) != 0) {
                sex = (Integer) SPUtils.get(this, USERSEX, 0);
            }
            if (!SPUtils.get(this, COMMUNITY, "0").equals("0")) {
                community = (String) SPUtils.get(this, COMMUNITY, "0");
                normalProjectId = (String) SPUtils.get(this, COMMUNITYID, "0");
            }
        } else {
            BToast.showText(this, "请先登录");
            return false;
        }

        return true;
    }

    @Override
    public String header() {
        return token;
    }

    @Override
    public List<String> imageList() {
        return imageList;
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public String userId() {
        return userId;
    }

    int nameType = 0;

    @Override
    public String realname() {
        if (realNameTv.getText().toString().equals(userName)) {
            nameType = 0;
        } else {
            nameType = 1;
        }
        return realNameTv.getText().toString().trim();
    }

    @Override
    public String avatar() {
        return avatar;
    }

    Integer sexType;
    int sexIsType = 0;

    @Override
    public Integer sex() {
        if (sexType != null) {
            if (sexType == sex) {
                sexIsType = 0;
            } else {
                sexIsType = 1;
            }
        }
        return sexType;
    }

    @Override
    public String phone() {
        return phoneTt.getText().toString().trim();
    }

    String projectId;
    int projectIdType = 0;

    @Override
    public String projectId() {
        if (projectId != null) {
            if (projectId.equals(normalProjectId)) {
                projectIdType = 0;
            } else {
                projectIdType = 1;
            }
        } else {
            projectIdType = 0;
        }
        return projectId;
    }

    String tenantId;

    @Override
    public String tenantId() {
        return tenantId;
    }

    @Override
    public void showToast(String content) {
        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {

    }

    String avatar;
    int avatarType = 0;

    @Override
    public void getData(UpImageBean upImageBean) {
        if (isImage == 1 && upImageBean.getResult() != null) {
            avatar = upImageBean.getResult();
            avatarType = 1;
            personPresenter.upDatePerson();
        }
    }

    @Override
    public void showProgress() {
        showLoding();
    }

    @Override
    public void hideProgress() {
        hideLoding();
    }

    @Override
    public void getData(PersonBean personBean) {
        if (personBean.getResult() != null) {
            BToast.showText(this, "修改成功");
            if (nameType == 1) {
                SPUtils.put(this, USERNAME, realNameTv.getText().toString().trim());
            }
            if (avatarType == 1) {
                SPUtils.put(this, USERIMAGE, avatar);
            }
            if (projectIdType == 1) {
                SPUtils.put(this, COMMUNITY, communityTv.getText().toString().trim());
                SPUtils.put(this, COMMUNITYID, projectId);
                SPUtils.put(this, TENANTID, tenantId);
            }
            if (sexIsType == 1) {
                SPUtils.put(this, USERSEX, sexType);
            }
            finish();
        }
    }
}
